<script setup lang='ts'>
import { computed, onMounted, ref } from 'vue'
import { useCounterStore } from '@/stores/users';
import { useCartStore } from '@/stores/cart'
import { Dialog, Notify } from 'vant';
import { useRouter } from 'vue-router';
const userStore = useCounterStore()
const cartStore = useCartStore()
const router = useRouter()
//  封装请求函数
const requestAPI = () => {
    cartStore.getDetailInfoHandler((userStore as any).userid)
}


// 发送请求获取购物车列表
onMounted(() => {
    requestAPI()
    cartStore.recommendlistHandler({ count: count.value, limitNum: 10 });
})

// TODO 获取购物车商品数据
const datailList = computed(() => {
    if (JSON.stringify(cartStore.datail) != '{}') {
        return cartStore.datail
    }
})
//TODO 推荐商品信息
const count = ref(1)  //请求参数
const loading = ref(false)  //上拉的加载效果
const finished = ref(false)
const onLoad = async () => {//触底触发onload事件
    loading.value = true;
    count.value++
    try {
        await cartStore.recommendlistHandler({ count: count.value, limitNum: 10 });
    } catch (error) {
        //没有获取到数据的时候,finished表示完成
        finished.value = true;//显示没有更多了
    }
}
//TODO 下拉
const refresh = ref(false)  //下拉的显示的状态
//下拉触发的函数
const onRefresh = () => {
    refresh.value = true;
    //再次发送请求,重新获取一遍数据
    requestAPI()
    //关闭下来的圈圈
    refresh.value = false;
}
//TODO 使用计算属性获取推荐的数据
const Recommendlist = computed(() => {
    return cartStore.recommendlist
})

// 计算总数量
//TODO 计算总数量
const sum = computed(() => {
    let number = 0;
    (datailList as any).value.forEach((item: { flag: any; num: number; }) => {
        if (item.flag) {
            number += item.num
        }
    })
    return number;
})
// 删除购物车数据
const delCard = (cartid: string) => {
    Dialog.confirm({
        title: '确认要删除商品信息吗?'
    }).then(() => { //点击的是确定
        //根据id删除内容
        cartStore.removeCartHandler(cartid)
        //再次获取数据
        requestAPI();
    })
        .catch(() => {//点击的取消

        });
}
// 商品数据量++
const updateNum = async (cartid: string, num: number) => {
    await cartStore.updatenumCartHandler({ cartid, num })
    // 重新渲染数据
    requestAPI();
}
//   当选状态更新
const checkSelectOne = async (cartid: string, flag: boolean) => {
    await cartStore.selectoneCartHandler({ cartid, flag })
    //   重新渲染数据
    requestAPI()
}
// 全选状态
// 计算属性对象的写法，使用set 修改状态
const isSelectAll = computed({
    get() {
        //购物车里面的数量和
        if ((datailList as any).value.length > 0) {
            return (datailList as any).value.every((item: any) => item.flag)
        }
    },
    async set(value) {
        //点击的全选                   
        await cartStore.checkCartAllHandler({ userid: userStore.userid, type: value })
        //重新读取服务器的数据
        requestAPI();
    }

})

// 提交订单
const onSubmit = async () => {
    try {
        if (totalPrice.value) {
            const result = await cartStore.addOrderCartHandler(userStore.userid)
            router.push("/order?time=" + result)
        } else {
            Dialog.alert({
                title: '请确认提交的商品',
                theme: 'round-button',
            }).then(() => {
                // on close
            });
        }
        //   `/order?item=${result}`
    } catch (error) {
        Notify("服务器异常")
    }
}

// TODO 使用计算属性计算总价
const totalPrice = computed(() => {
    // 定义变量用于接收总价
    let sum = 0;
    datailList.value?.forEach(item => {
        if ((item as any).flag) {
            sum += (item as any).num * (item as any).originprice
        }
    })
    return sum * 100
})
</script>
<template>
    <div class="cart">
        <!-- 头部 -->
        <van-nav-bar :title="`购物车(${sum})`" left-text="返回" left-arrow @click-left="$router.back()" />
        <!-- 下拉刷新 -->
        <van-pull-refresh v-model="refresh" @refresh="onRefresh">
            <!-- 空的购物车 -->
            <div v-if="(datailList as any).length <= 0">
                <van-empty description="购物车空空如也,快去购物吧！">
                    <van-button round type="danger" class="bottom-button">去购物</van-button>
                </van-empty>
            </div>
            <!-- 购物车列表  -->
            <div class="cart">
                <van-swipe-cell v-for="cart in datailList" :key="(cart as any).cartid">
                    <!-- 复选框 -->
                    <van-checkbox v-model="(cart as any).flag"
                        @click="checkSelectOne((cart as any).cartid, (cart as any).flag)"></van-checkbox>
                    <!-- 商品 -->
                    <van-card :price="(cart as any).originprice" :title="(cart as any).proname" class="goods-card"
                        :thumb="(cart as any).img1" />
                    <!-- 步进器 -->
                    <van-stepper class="stepper" v-model="(cart as any).num" theme="round" button-size="22"
                        disable-input @click="updateNum((cart as any).cartid, (cart as any).num)" />
                    <template #right>
                        <van-button square text="删除" type="danger" class="delete-button"
                            @click="delCard((cart as any).cartid)" />
                    </template>
                </van-swipe-cell>
            </div>
            <!-- TODO 分割线 -->
            <van-divider>可能你还想要</van-divider>
            <!-- 推荐商品 -->
            <!-- 推荐商品信息 -->
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <div class="goodsList">
                    <div class="goodsListItem" v-for="item in Recommendlist" :key="(item as any).proid"
                        @click="$router.push(`/detail/${(item as any).proid}`)">
                        <img :src="(item as any).img1" alt="">
                        <p>{{ (item as any).desc }}</p>
                        <span>¥ {{ (item as any).originprice }}</span>
                    </div>
                </div>
            </van-list>
        </van-pull-refresh>
        <!-- 提交订单 -->
        <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit">
            <van-checkbox v-model="isSelectAll">全选</van-checkbox>
        </van-submit-bar>

    </div>
</template>
<style scoped lang='scss'>
.goodsList {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;

    .goodsListItem {
        width: 45%;

        p {
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2; //多行在这里修改数字即可
            overflow: hidden;
            /* autoprefixer: ignore next */
            -webkit-box-orient: vertical;
        }

        img {
            height: 300px;
        }

        span {
            color: red;
        }
    }

    &::after {
        content: "";
        display: block;
        width: 45%;
    }
}


.cart {
    position: relative;
    padding-bottom: 100px;

    .van-stepper {
        position: absolute;
        bottom: 20px;
        right: 20px;
    }
}

.stepper {
    margin-right: 10px;
}

.van-checkbox {

    margin-left: 20px;

}

:deep(.van-card__title) {
    width: 420px;
}

:deep(.van-swipe-cell__wrapper) {
    display: flex;
}

.bottom-button {
    width: 160px;
    height: 40px;
}

.goods-card {
    margin: 0;
}

.delete-button {
    height: 100%;
}
</style>